package com.ftg.learn.day15.interfacexml.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

/**
 * @author 布衣
 */
public  class MapperUtil {

    public MapperUtil(String path){
        this.path = path;
    }

    private SqlSession sqlSession;

    private SqlSessionFactory sqlSessionFactory;

    private String path;

    /**
     * 通过解析zong.xml得到相关的参数信息
     *
     * @return
     */
    public Reader getXmlInfo() throws IOException {
        return Resources.getResourceAsReader(path);
    }

    /**
     * 根据给定的信息生成sqlSessionFactorybuilder
     *
     * @return
     */
    public SqlSessionFactoryBuilder getSqlSessionFactoryBuilder() {
        return new SqlSessionFactoryBuilder();
    }

    /**
     * 根据sqlSessionFactoryBuilder生成sqlSessionFactory
     *
     * @return
     * @throws IOException
     */
    public SqlSessionFactory getSqlSessionFactory() throws IOException {
        if (sqlSessionFactory == null) {
            return this.getSqlSessionFactoryBuilder().build(this.getXmlInfo());
        }
        return sqlSessionFactory;
    }

    /**
     * 获取sqlSession
     *
     * @return
     * @throws IOException
     */
    public SqlSession getSqlSession() throws IOException {
        if (sqlSession == null) {
            return this.getSqlSessionFactory().openSession();
        }
        return sqlSession;
    }

    /**
     * 获取mapper
     * @param mapper 关联对象
     * @return
     * @param <T>
     * @throws IOException
     */
    public <T> T getMapper(Class<T> mapper) throws IOException {
        return getSqlSession().getMapper(mapper);
    }


    public void myCommit(){
        if(sqlSession != null){
            sqlSession.commit();
        }
    }

    public void myRollback(){
        if(sqlSession != null){
            sqlSession.rollback();
        }
    }

    public void myClose(){
        if(sqlSession != null){
            sqlSession.close();
        }
    }
}
